//
//  CHWebProBar.swift
//  bridging_js
//
//  Created by cyptt on 2021/9/13.
//

import UIKit
import CHSimpleUI
class CHWebProBar: NSObject {

    var displayLink: CADisplayLink!
    var currentValue: CGFloat = 0;
    var progressBar: CHProgressBar! //进度条
   

    func initBar(result:String) {
        currentValue = 0
        progressBar = CHProgressBar()
        var baseModelM:CHWebBaseModel<CHWebProgressStyle>?
        if let baseModel = CHWebBaseModel<CHWebProgressStyle>.deserialize(from: result ){
            baseModelM = baseModel
        }
        let webProStyle:CHWebProgressStyle = baseModelM!.body!
        let deaultColor:UIColor? = UIColor.init(hexString: webProStyle.deaultColor!)
        let trackColor:UIColor? = UIColor.init(hexString: webProStyle.trackColor!)
        let percentColor:UIColor? = UIColor.init(hexString: webProStyle.percentColor!)
        progressBar.addAnimate(view: progressBar.initView(deaultColor: deaultColor!, trackColor: trackColor!, percentColor: percentColor!))
//        displayLink = CADisplayLink.init(target: self, selector: #selector(displayLinkRun))
//        displayLink.add(to: RunLoop.current, forMode: RunLoop.Mode.default)
//        progressBar.displayLink = displayLink
    }
    
    func startBar(result:String) {
        var baseModelM:CHWebBaseModel<String>?
        if let baseModel = CHWebBaseModel<String>.deserialize(from: result ){
            baseModelM = baseModel
        }
        let percent:Float = Float(baseModelM?.body! ?? "0")!
        
        
        progressBar.passValue(currentValue: CGFloat(percent), allValue: 1.0)
    }
    /**
     结束进度条
     */
    func stopBar(){
        progressBar.stop()
    }
    
    @objc func displayLinkRun(){
        print("-----currentvalue----",currentValue)
        if currentValue > 1 {
            //加载完成 关闭定时器，隐藏进度条
            displayLink.invalidate()
            displayLink = nil
            progressBar.removeFromSuperview()
        }
        else{
            currentValue = currentValue + 0.005;
            progressBar.passValue(currentValue: currentValue, allValue: 1.0)
        }
    }
}
